package com.ruikc.study.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.ruikc.study.demo.dio.LoginRequest;
import com.ruikc.study.demo.util.JwtUtils;
import com.ruikc.study.demo.util.Result;

@RestController
public class AuthController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @PostMapping("/login")
    public Result login(@RequestBody LoginRequest request) {
        // 手动执行认证（需实现 UserDetailsService）
        Authentication authentication = authenticationManager.authenticate(
            new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword())
        );

        if (authentication.isAuthenticated()) {
            // 生成 JWT
            String token = JwtUtils.generateToken(request.getUsername());
            return Result.ok().data("token", token).data("username", request.getUsername());
        } else {
            return Result.error().message("认证失败");
        }
    }
}